package com.envmonitor.domain.service;

import com.envmonitor.domain.model.Device;
import com.envmonitor.domain.repository.DeviceRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class DeviceService {
    
    private final DeviceRepository deviceRepository;
    
    public List<Device> getAllDevices() {
        return deviceRepository.findAll();
    }
    
    public Optional<Device> getDeviceById(Long id) {
        return deviceRepository.findById(id);
    }
    
    public List<Device> getDevicesByType(Device.DeviceType type) {
        return deviceRepository.findByType(type);
    }
    
    public List<Device> getActiveDevices() {
        return deviceRepository.findByActiveTrue();
    }
    
    @Transactional
    public Device saveDevice(Device device) {
        return deviceRepository.save(device);
    }
    
    @Transactional
    public void deleteDevice(Long id) {
        deviceRepository.deleteById(id);
    }
    
    @Transactional
    public Optional<Device> updateDeviceStatus(Long id, boolean active) {
        Optional<Device> deviceOpt = deviceRepository.findById(id);
        if (deviceOpt.isPresent()) {
            Device device = deviceOpt.get();
            device.setActive(active);
            return Optional.of(deviceRepository.save(device));
        }
        return Optional.empty();
    }
}